package com.fzg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fzg.common.enums.ResponseWrapper;
import com.fzg.common.model.recruitmentInfoManage.param.*;
import com.fzg.common.model.recruitmentInfoManage.result.*;
import com.fzg.common.tool.CommonTool;
import com.fzg.common.tool.ToolForDateTime;
import com.fzg.entity.Enterprise;
import com.fzg.entity.RecruitmentEnterprise;
import com.fzg.entity.RecruitmentInfor;
import com.fzg.entity.User;
import com.fzg.mapper.EnterpriseMapper;
import com.fzg.mapper.RecruitmentEnterpriseMapper;
import com.fzg.mapper.RecruitmentInforMapper;
import com.fzg.mapper.UserMapper;
import com.fzg.service.RecruitmentInforService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 招聘信息表 服务实现类
 * </p>
 *
 * @author fzg
 * @since 2021-12-13
 */
@Service
public class RecruitmentInforServiceImpl extends ServiceImpl<RecruitmentInforMapper, RecruitmentInfor> implements RecruitmentInforService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired RecruitmentInforMapper recruitmentInforMapper;

    @Autowired
    private RecruitmentEnterpriseMapper recruitmentEnterpriseMapper;

    @Override
    public ResponseWrapper getRecruitmentInfoList(GetResruitListParam param) {

        // 加工页码
        param.setPage((param.getPage() - 1) * param.getPageRow()); //处理分页条件

        // 加工搜索条件（企业名称）
        if (param.getEnterpriseName() != null && !param.getEnterpriseName().equals("")){
            param.setEnterpriseName("%" + param.getEnterpriseName() + "%");
        }

        // 加工搜索条件（部门名称）
        if (param.getSalary() != null && !param.getSalary().equals("")){
            param.setSalary("%" + param.getSalary() + "%");
        }

        // 加工搜索条件（岗位名称）
        if (param.getPositionName() != null && !param.getPositionName().equals("")){
            param.setPositionName("%" + param.getPositionName() + "%");
        }

        // 返回结果
        GetRecritListResult result = new GetRecritListResult();

        // 查询当前登录人（企业）
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getIsAdmin, 1)
                .eq(User::getAccountNumber, param.getAccount()));
        if (user != null){
            // 当前登录的是管理员，返回所有企业的招聘信息
            List<Map<String, Object>> infoListMap = recruitmentInforMapper.getRecruitmentInfoListMap(param);
            List<GetRecritListResultItem> infoList = CommonTool.mapListToBeanList(infoListMap, GetRecritListResultItem.class);
            result.setRecruitmentInfoList(infoList);
            result.setTotalNum(recruitmentInforMapper.getAdminRecruitmentInfoListTotal(param));
        }else {
            // 当前登陆的是企业，只要返回这个登陆企业的招聘信息列表即可
            List<GetRecritListResultItem> infoList = CommonTool.mapListToBeanList(recruitmentInforMapper.getRecruitmentInfoListMapByEnterpriseAccount(param), GetRecritListResultItem.class);
            result.setRecruitmentInfoList(infoList);
            result.setTotalNum(recruitmentInforMapper.getRecruitmentListByEnterpriseAccountTotal(param));
        }
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    public ResponseWrapper getEnterpriseList(GetCompanyListParam param) {

        // 返回结果
        ArrayList<GetCompanyListResult> result = new ArrayList<>();

        // 查询当前登陆的账号
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccountNumber, param.getAccount()));
        if (user != null){
            // 查询当前登陆的账号是否是管理员，如果是管理员则返回所有的企业列表；
            List<Enterprise> enterprises = enterpriseMapper.selectList(null);
            for (Enterprise enterpris : enterprises) {
                GetCompanyListResult company = new GetCompanyListResult();
                company.setAid(enterpris.getAid());
                company.setName(enterpris.getName());
                result.add(company);
            }
        }else {
            // 如果当前登录的账号不是管理员，则查询对应的企业，
            Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
            GetCompanyListResult company = new GetCompanyListResult();
            company.setAid(enterprise.getAid());
            company.setName(enterprise.getName());
            result.add(company);
        }
        return ResponseWrapper.markSuccess(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper editOrAddRecruitInfo(EditOrAddRecruitInfoParam param) {

        if (param.getAid()==-1){
            // 新增招聘信息
            RecruitmentInfor recruitmentInfor = recruitmentInforMapper.selectOne(new LambdaQueryWrapper<RecruitmentInfor>().orderByDesc(RecruitmentInfor::getAid).last("limit 1"));
            int insertRecruitmentInfor = recruitmentInforMapper.insert(new RecruitmentInfor() {{
                setAid(recruitmentInfor.getAid() + 1);
                setSalary(param.getSalary());
                setGender(param.getGender());
                setRecruimentTime(ToolForDateTime.stringToLocalTime(param.getRecruimentTime() + " " + "12:00:00"));
                setRecruitmentAddress(param.getRecruitmentAddress());
                setPosition(param.getPosName());
                setContent(param.getContent());
                if (param.getState().equals("是")){
                    setState(1);
                }else {
                    setState(0);
                }
            }});
            if (insertRecruitmentInfor > 0){
                // 新增recruitment_enterprise表
                int insertRecruitmentEnterprise = recruitmentEnterpriseMapper.insert(new RecruitmentEnterprise() {{
                    setRecuitmentaid(recruitmentInfor.getAid() + 1);
                    setEnterpriseaid(param.getEnterpriseAid());
                }});
                if (insertRecruitmentEnterprise > 0){
                    return ResponseWrapper.markCustomSuccess("新增成功！");
                }
            }

        }else {
            // 修改招聘信息
            int updateEnterPrise = enterpriseMapper.update(null, new LambdaUpdateWrapper<Enterprise>()
                    .eq(Enterprise::getAid, param.getEnterpriseAid())
                    .set(Enterprise::getLeader, param.getLeader())
                    .set(Enterprise::getPhone, param.getPhone()));
            if (updateEnterPrise > 0){
                // 修改recruitment_infor表
                int restate;
                if (param.getState().equals("是")){
                    restate = 1;
                }else {
                    restate = 0;
                }
                int updateRecruitmentInfor = recruitmentInforMapper.update(null, new LambdaUpdateWrapper<RecruitmentInfor>()
                        .eq(RecruitmentInfor::getAid, param.getAid())
                        .set(RecruitmentInfor::getPosition, param.getPosName())
                        .set(RecruitmentInfor::getSalary, param.getSalary())
                        .set(RecruitmentInfor::getRecruitmentAddress, param.getRecruitmentAddress())
                        .set(RecruitmentInfor::getRecruimentTime, ToolForDateTime.stringToLocalTime(param.getRecruimentTime() + " " + "12:00:00"))
                        .set(RecruitmentInfor::getGender, param.getGender())
                        .set(RecruitmentInfor::getState,restate)
                        .set(RecruitmentInfor::getContent, param.getContent()));
                if (updateRecruitmentInfor > 0){
                    // 修改recruitment_enterprise表
                    int updateRecruitmentEnterprise = recruitmentEnterpriseMapper.update(null, new LambdaUpdateWrapper<RecruitmentEnterprise>()
                            .eq(RecruitmentEnterprise::getRecuitmentaid, param.getAid())
                            .set(RecruitmentEnterprise::getEnterpriseaid, param.getEnterpriseAid()));
                    if (updateRecruitmentEnterprise > 0){
                        return ResponseWrapper.markCustomSuccess("修改成功！");
                    }
                }
            }
        }
        return ResponseWrapper.markError();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper delRecruInfo(DelRecruitInfoParam param) {
        //  1. 首先通过招聘信息aid和企业aid找到recruitment_enterprise表的aid。
        RecruitmentEnterprise recruitmentEnterprise = recruitmentEnterpriseMapper.selectOne(new LambdaQueryWrapper<RecruitmentEnterprise>()
                .eq(RecruitmentEnterprise::getRecuitmentaid, param.getRecruitInfoAid())
                .eq(RecruitmentEnterprise::getEnterpriseaid, param.getEnterpriseAid()));
        //   2. 其次删除recruitment_enterprise表aid对应的那一条数据。
        int deleteRecruitEnterprise = recruitmentEnterpriseMapper.deleteById(recruitmentEnterprise.getAid());
        if (deleteRecruitEnterprise > 0){
            //   3. 最后删除根据招聘信息aid删除recruitment_infor表的那一天数据。
            int deleteRecruitInfo = recruitmentInforMapper.deleteById(param.getRecruitInfoAid());
            if (deleteRecruitInfo > 0){
                return ResponseWrapper.markCustomSuccess("这条招聘信息删除成功！");
            }
        }
        return ResponseWrapper.markError();
    }

    /**
     * 获取公司所有招聘信息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper getCompanyRecruitInfoList(GetCompanyRecruitInfoListParam param) {
        Enterprise enterprise = enterpriseMapper.selectOne(new LambdaQueryWrapper<Enterprise>().eq(Enterprise::getAccountNumber, param.getAccount()));
        List<RecruitmentEnterprise> recruitList = recruitmentEnterpriseMapper.selectList(new LambdaQueryWrapper<RecruitmentEnterprise>().eq(RecruitmentEnterprise::getEnterpriseaid, enterprise.getAid()));
        ArrayList<RecruitmentInfor> result = new ArrayList<>();
        for (RecruitmentEnterprise item : recruitList) {
            RecruitmentInfor recruitmentInfor = recruitmentInforMapper.selectById(item.getRecuitmentaid());
            result.add(recruitmentInfor);
        }
        System.out.println("范占国" + result);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 获取招聘详情的所有信息
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper getPositionAllInfo(GetPositionAllInfoParam param) {
        Enterprise enterprise = enterpriseMapper.selectById(param.getCompanyAid());
        RecruitmentInfor recruitmentInfor = recruitmentInforMapper.selectById(param.getRecruitmentInfoAid());
        GetPositionAllInfoResult result = new GetPositionAllInfoResult();

        result.setCompanyAid(enterprise.getAid());
        result.setCompanyName(enterprise.getName());
        result.setCompanyAvatarUrl(enterprise.getAvatar());
        result.setCompanyPeopleCount(enterprise.getEmployeeCount() + "人");
        result.setCompanyAddress(enterprise.getAddress());
        result.setCompanyIntroduction(enterprise.getIntroduction());
        result.setCompanyAccount(enterprise.getAccountNumber());

        RecruitmentEnterprise companyRecruit = recruitmentEnterpriseMapper.selectOne(new LambdaQueryWrapper<RecruitmentEnterprise>()
                .eq(RecruitmentEnterprise::getEnterpriseaid, param.getCompanyAid())
                .eq(RecruitmentEnterprise::getRecuitmentaid, param.getRecruitmentInfoAid()));

        result.setCompanyRecruitAid(companyRecruit.getAid());
        result.setRecruitmentInfoAid(recruitmentInfor.getAid());
        result.setPublishTime(ToolForDateTime.LocalDateTimeToStringToDate(companyRecruit.getCreateTime()));
        result.setPositionName(recruitmentInfor.getPosition());
        result.setSalary(recruitmentInfor.getSalary());
        result.setWorkAddress(recruitmentInfor.getRecruitmentAddress());
        result.setJobType(recruitmentInfor.getRecruitType());
        result.setEducation(recruitmentInfor.getEducation());
        result.setRecruitPeopleCount(recruitmentInfor.getRequirePeopleCount() + "人");
        result.setPositionDecription(recruitmentInfor.getContent());
        result.setInvalid(!recruitmentInfor.getState().equals(1));
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 得到全部公司的招聘信息列表
     *
     * @param param 参数类
     */
    @Override
    public ResponseWrapper getAllcompanyRecruitList(GetAllcompanyRecruitListParam param) {

        // 加工页码
        param.setPage((param.getPage() - 1) * param.getPageRow()); //处理分页条件

        // 加工搜索条件（companyName）
        if (param.getCompanyName() != null && !param.getCompanyName().equals("")){
            param.setCompanyName("%" + param.getCompanyName() + "%");
        }

        // 加工搜索条件（positionName）
        if (param.getPositionName() != null && !param.getPositionName().equals("")){
            param.setPositionName("%" + param.getPositionName() + "%");
        }

        // 加工搜索条件（recruit_type）
        if (param.getRecruitType() != null && !param.getRecruitType().equals("")){
            param.setRecruitType("%" + param.getRecruitType() + "%");
        }

        GetAllCompanyRecruitmentListResult result = new GetAllCompanyRecruitmentListResult();

        result.setTotalNum(recruitmentInforMapper.getAllCompanyRecruitAndCompanyInfoTotalCount(param));
        result.setCompanyRecruitList(CommonTool.mapListToBeanList(recruitmentInforMapper.getAllCompanyRecruitAndCompanyInfo(param),GetAllCompanyRecruitmentListResultItem.class));

        return ResponseWrapper.markSuccess(result);

    }
}
